<template>
  <div class="mb-[10px] flex justify-between">
    <CardTitle :title="t('batchMentor.select.mentor')" />
    <SendChatTeacher :user-ids="ids" />
  </div>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="70px"
    >
      <el-form-item :label="t('systemUser.fields.nickname')" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.nickname')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-120px"
        />
      </el-form-item>
      <el-form-item class="!mr-0">
        <el-button @click="handleQuery">
          <Icon icon="ep:search" />
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" />
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <vxe-table
    ref="tableRef"
    v-loading="loading"
    :data="list"
    stripe
    :row-config="{ keyField: 'id' }"
    :checkbox-config="{ reserve: true }"
    :column-config="{ resizable: true }"
    :size="vxeTableSize"
    @checkbox-all="collectSelect"
    @checkbox-change="collectSelect"
  >
    <vxe-column type="checkbox" width="50" align="center" />
    <vxe-column
      :title="t('systemUser.fields.jobCode')"
      field="jobCode"
      align="center"
      show-header-overflow
      show-overflow
      min-width="60"
    />
    <vxe-column
      :title="t('systemUser.fields.nickname')"
      field="nickname"
      align="center"
      show-header-overflow
      show-overflow
      min-width="60"
    />
    <vxe-column
      :title="t('systemUser.fields.mobile')"
      field="mobile"
      align="center"
      show-header-overflow
      show-overflow
      min-width="95"
    />
    <vxe-column
      :title="t('systemUser.fields.deptName')"
      field="deptName"
      align="center"
      show-header-overflow
      show-overflow
      min-width="100"
    />
    <vxe-column
      :title="t('systemUser.fields.zcm')"
      field="zcm"
      align="center"
      show-header-overflow
      show-overflow
      min-width="70"
    />
    <vxe-column
      :title="t('systemUser.fields.workingStatus')"
      field="workingStatus"
      align="center"
      show-header-overflow
      show-overflow
      min-width="60"
    >
      <template #default="scope">
        <dict-tag
          v-if="scope.row.workingStatus"
          :type="DICT_TYPE.WORKING_STATUS"
          :value="scope.row.workingStatus"
        />
      </template>
    </vxe-column>
    <vxe-column
      :title="t('batchMentor.fields.quota')"
      align="center"
      show-header-overflow
      show-overflow
      min-width="90"
    >
      <template #default="scope">
        <el-tooltip class="box-item" effect="dark" placement="left">
          <template #content>
            <p>{{ t('batchMentor.fields.quota1') }}: {{ scope.row.quota1 }}</p>
            <p>{{ t('batchMentor.fields.quota2') }}: {{ scope.row.quota2 }}</p>
            <p>{{ t('batchMentor.fields.quota3') }}: {{ scope.row.quota3 }}</p>
            <p>{{ t('batchMentor.fields.quota4') }}: {{ scope.row.quota4 }}</p>
            <p>{{ t('batchMentor.fields.quota5') }}: {{ scope.row.quota5 }}</p>
          </template>
          {{ scope.row.quota1 }}/{{ scope.row.quota2 }}/{{ scope.row.quota3 }}/{{
            scope.row.quota4
          }}/{{ scope.row.quota5 }}
        </el-tooltip>
      </template>
    </vxe-column>
    <vxe-column
      :title="t('common.operate')"
      field="operator"
      align="center"
      fixed="right"
      width="80"
    >
      <template #default="scope">
        <el-button link type="primary" @click="handleUpdateQuota(scope.row)">
          {{ t('batchMentor.select.setQuota') }}
        </el-button>
      </template>
    </vxe-column>
  </vxe-table>
  <!-- 分页 -->
  <Pagination
    class="justify-center"
    :total="total"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
    layout="total, prev, pager, next"
  />
  <Dialog :title="t('batchMentor.select.setQuota')" v-model="dialogVisible" width="400">
    <CardTitle class="block mb-[10px]" :title="currentVo.nickname ?? ''" />

    <el-form :model="currentVo" label-position="top" v-loading="formLoading">
      <el-form-item :label="t('batchMentor.fields.quota1')">
        <el-input-number
          v-model="currentVo.quota1"
          class="better-number-input !w-1/1"
          :min="0"
          :value-on-clear="0"
          :controls="false"
        />
      </el-form-item>
      <el-form-item :label="t('batchMentor.fields.quota2')">
        <el-input-number
          v-model="currentVo.quota2"
          class="better-number-input !w-1/1"
          :min="0"
          :value-on-clear="0"
          :controls="false"
        />
      </el-form-item>
      <el-form-item :label="t('batchMentor.fields.quota3')">
        <el-input-number
          v-model="currentVo.quota3"
          class="better-number-input !w-1/1"
          :min="0"
          :value-on-clear="0"
          :controls="false"
        />
      </el-form-item>
      <el-form-item :label="t('batchMentor.fields.quota4')">
        <el-input-number
          v-model="currentVo.quota4"
          class="better-number-input !w-1/1"
          :min="0"
          :value-on-clear="0"
          :controls="false"
        />
      </el-form-item>
      <el-form-item :label="t('batchMentor.fields.quota5')">
        <el-input-number
          v-model="currentVo.quota5"
          class="better-number-input !w-1/1"
          :min="0"
          :value-on-clear="0"
          :controls="false"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleSubmit" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/store/modules/app'
import { BatchMentorApi, BatchMentorSelectedRespVO, BatchMentorVO } from '@/api/recruit/batchmentor'
import { CardTitle } from '@/components/Card'
import SendChatTeacher from '@/components/SendChatTeacher/index.vue'
import type { VxeTableInstance } from 'vxe-table'
import _ from 'lodash-es'
import { DICT_TYPE } from '@/utils/dict'

const props = defineProps<{
  batchId: string
}>()

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const currentVo = ref<Partial<BatchMentorSelectedRespVO>>({})

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const loading = ref(false)
const list = ref<BatchMentorSelectedRespVO[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  batchId: props.batchId,
  nickname: undefined
})
const queryFormRef = ref() // 搜索的表单

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const getList = async () => {
  loading.value = true
  try {
    const data = await BatchMentorApi.getSelectedMentorByBatchId(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const tableRef = ref<VxeTableInstance>()

const remove = async () => {
  if (loading.value) {
    throw new Error()
  }
  // 获取所有已选择的数据
  const selectedData = [
    ...(tableRef.value?.getCheckboxRecords() ?? []),
    ...(tableRef.value?.getCheckboxReserveRecords() ?? [])
  ]
  if (selectedData.length === 0) {
    throw new Error()
  }

  try {
    await message.confirm(t('batchMentor.select.removeConfirm'))
  } catch {
    throw new Error()
  }

  loading.value = true
  try {
    await BatchMentorApi.removeBatchMentor(
      props.batchId,
      selectedData.map((item) => {
        return {
          userId: item.userId
        }
      })
    )
    // 清空复选框
    tableRef.value?.clearCheckboxRow()
  } finally {
    loading.value = false
    getList()
  }
}

const handleUpdateQuota = (row: BatchMentorSelectedRespVO) => {
  currentVo.value = _.cloneDeep(row)
  dialogVisible.value = true
}

const clean = () => {
  list.value = []
  total.value = 0
}

const handleSubmit = async () => {
  formLoading.value = true
  try {
    await BatchMentorApi.updateBatchMentor(currentVo.value as BatchMentorVO)
  } finally {
    formLoading.value = false
    dialogVisible.value = false
    getList()
  }
}

const ids = ref<number[]>([])
const collectSelect = () => {
  ids.value = [
    ...(tableRef.value?.getCheckboxRecords() ?? []),
    ...(tableRef.value?.getCheckboxReserveRecords() ?? [])
  ].map((item) => item.userId)
}

watch(
  () => props.batchId,
  () => {
    if (props.batchId) {
      getList()
    }
  },
  {
    immediate: true
  }
)

defineExpose({
  remove,
  getList,
  clean
})
</script>
